package com.stm.bi.repository;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.stm.bi.jdbc.DataSourceEnum;
import com.stm.bi.jdbc.DataSourceSwitch;
import com.stm.bi.repository.dataobject.EtlRecordDO;
import com.stm.bi.repository.mapper.EtlRecordMapper;
import com.stm.framework.core.tookit.BeanToolkit;
import com.stm.framework.core.util.DateUtils;
import com.stm.framework.core.util.LocalDateTimeUtil;
import com.stm.framework.redisson.annotation.SyncLock;
import com.stm.framework.repository.BaseRepository;
import com.stm.framework.snowflake.Snowflake;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * 同步记录-仓储
 *
 * @author 阿俊
 * @date 2024-01-22
 */
@Repository
public class EtlRecordRepository extends BaseRepository<EtlRecordMapper, EtlRecordDO, EtlRecordDO> {

    @Resource
    private Snowflake snowflake;

    @SyncLock(key = "#p0+'-'+#p02")
    public EtlRecordDO getAndCreateIfAbsent(Long orgId,String orgName, String taskName) {
        LambdaQueryWrapper<EtlRecordDO> queryWrapper = Wrappers.<EtlRecordDO>lambdaQuery()
                .eq(EtlRecordDO::getOrgId, orgId)
                .eq(EtlRecordDO::getTaskName, taskName);
        EtlRecordDO record = this.baseMapper.selectOne(queryWrapper);
        if (record == null) {
            record = new EtlRecordDO();
            record.setId(snowflake.nextId());
            record.setOrgId(orgId);
            record.setOrgName(orgName);
            record.setTaskName(taskName);
            Date date = DateUtils.parseDate(LocalDateTime.now().getYear() - 3 + "-01-01");
            record.setLastEtlTime(LocalDateTimeUtil.date2LocalDateTime(date));
            this.save(record);
        }
        return BeanToolkit.instance().copy(record, EtlRecordDO.class);
    }
}
